package com.frinder.wx.base.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.frinder.wx.base.api.tuling.ITuLingService;
import com.frinder.wx.base.api.tuling.payload.TuLingRequest;
import com.frinder.wx.base.api.tuling.payload.TuLingResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.weixin4j.model.message.OutputMessage;
import org.weixin4j.model.message.normal.TextInputMessage;
import org.weixin4j.model.message.output.TextOutputMessage;

/**
 * @ClassName MessageService
 * @Description //TODO
 * @Author frinder
 * @Date 2018/12/6 15:37
 * @Version 1.0
 */
@Slf4j
@Service
public class MessageService {

    private final ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private ITuLingService tuLingService;

    public OutputMessage callTuLing(TextInputMessage msg) {
        TextOutputMessage message = new TextOutputMessage();
        try {
            TuLingRequest request = new TuLingRequest().text(msg.getContent());
            log.info("*** 请求图灵机器人，消息：{}", request);
            String data = tuLingService.v2(request);
            log.info("*** 图灵机器人响应：{}", data);
            TuLingResponse response = mapper.readValue(data, TuLingResponse.class);
            message.setContent(
                    response.getResults().stream()
                            .filter(o -> "text".equals(o.getResultType()))
                            .map(o -> o.getValues().getText())
                            .findFirst()
                            .orElse("哈哈，没找到！！！")
            );
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            message.setContent("我什么也不知道了！！！");
        }
        return message;
    }

}
